﻿#region Using directives

using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;

using TicketManager.Entities;
using TicketManager.Data;

#endregion

namespace TicketManager.Data.Bases
{	
	///<summary>
	/// This class is the base class for any <see cref="PhimProviderBase"/> implementation.
	/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
	///</summary>
	public abstract partial class PhimProviderBaseCore : EntityProviderBase<TicketManager.Entities.Phim, TicketManager.Entities.PhimKey>
	{		
		#region Get from Many To Many Relationship Functions
		#endregion	
		
		#region Delete Methods

		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to delete.</param>
		/// <returns>Returns true if operation suceeded.</returns>
		public override bool Delete(TransactionManager transactionManager, TicketManager.Entities.PhimKey key)
		{
			return Delete(transactionManager, key.PhimId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="_phimId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public bool Delete(System.Int32 _phimId)
		{
			return Delete(null, _phimId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_phimId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public abstract bool Delete(TransactionManager transactionManager, System.Int32 _phimId);		
		
		#endregion Delete Methods
		
		#region Get By Foreign Key Functions
		#endregion

		#region Get By Index Functions
		
		/// <summary>
		/// 	Gets a row from the DataSource based on its primary key.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to retrieve.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <returns>Returns an instance of the Entity class.</returns>
		public override TicketManager.Entities.Phim Get(TransactionManager transactionManager, TicketManager.Entities.PhimKey key, int start, int pageLength)
		{
			return GetByPhimId(transactionManager, key.PhimId, start, pageLength);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the primary key PK_phim index.
		/// </summary>
		/// <param name="_phimId"></param>
		/// <returns>Returns an instance of the <see cref="TicketManager.Entities.Phim"/> class.</returns>
		public TicketManager.Entities.Phim GetByPhimId(System.Int32 _phimId)
		{
			int count = -1;
			return GetByPhimId(null,_phimId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_phim index.
		/// </summary>
		/// <param name="_phimId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="TicketManager.Entities.Phim"/> class.</returns>
		public TicketManager.Entities.Phim GetByPhimId(System.Int32 _phimId, int start, int pageLength)
		{
			int count = -1;
			return GetByPhimId(null, _phimId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_phim index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_phimId"></param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="TicketManager.Entities.Phim"/> class.</returns>
		public TicketManager.Entities.Phim GetByPhimId(TransactionManager transactionManager, System.Int32 _phimId)
		{
			int count = -1;
			return GetByPhimId(transactionManager, _phimId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_phim index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_phimId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="TicketManager.Entities.Phim"/> class.</returns>
		public TicketManager.Entities.Phim GetByPhimId(TransactionManager transactionManager, System.Int32 _phimId, int start, int pageLength)
		{
			int count = -1;
			return GetByPhimId(transactionManager, _phimId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_phim index.
		/// </summary>
		/// <param name="_phimId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="TicketManager.Entities.Phim"/> class.</returns>
		public TicketManager.Entities.Phim GetByPhimId(System.Int32 _phimId, int start, int pageLength, out int count)
		{
			return GetByPhimId(null, _phimId, start, pageLength, out count);
		}
		
				
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_phim index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_phimId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns an instance of the <see cref="TicketManager.Entities.Phim"/> class.</returns>
		public abstract TicketManager.Entities.Phim GetByPhimId(TransactionManager transactionManager, System.Int32 _phimId, int start, int pageLength, out int count);
						
		#endregion "Get By Index Functions"
	
		#region Custom Methods
		
		
		#endregion

		#region Helper Functions	
		
		/// <summary>
		/// Fill a TList&lt;Phim&gt; From a DataReader.
		/// </summary>
		/// <param name="reader">Datareader</param>
		/// <param name="rows">The collection to fill</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">number of rows.</param>
		/// <returns>a <see cref="TList&lt;Phim&gt;"/></returns>
		public static TList<Phim> Fill(IDataReader reader, TList<Phim> rows, int start, int pageLength)
		{
			NetTiersProvider currentProvider = DataRepository.Provider;
            bool useEntityFactory = currentProvider.UseEntityFactory;
            bool enableEntityTracking = currentProvider.EnableEntityTracking;
            LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy;
			Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType;
			
			// advance to the starting row
			for (int i = 0; i < start; i++)
			{
				if (!reader.Read())
				return rows; // not enough rows, just return
			}
			for (int i = 0; i < pageLength; i++)
			{
				if (!reader.Read())
					break; // we are done
					
				string key = null;
				
				TicketManager.Entities.Phim c = null;
				if (useEntityFactory)
				{
					key = new System.Text.StringBuilder("Phim")
					.Append("|").Append((System.Int32)reader[((int)PhimColumn.PhimId - 1)]).ToString();
					c = EntityManager.LocateOrCreate<Phim>(
					key.ToString(), // EntityTrackingKey
					"Phim",  //Creational Type
					entityCreationFactoryType,  //Factory used to create entity
					enableEntityTracking); // Track this entity?
				}
				else
				{
					c = new TicketManager.Entities.Phim();
				}
				
				if (!enableEntityTracking ||
					c.EntityState == EntityState.Added ||
					(enableEntityTracking &&
					
						(
							(currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) ||
							(currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged)
						)
					))
				{
					c.SuppressEntityEvents = true;
					c.PhimId = (System.Int32)reader[((int)PhimColumn.PhimId - 1)];
					c.TenPhim = (System.String)reader[((int)PhimColumn.TenPhim - 1)];
					c.LichChieuBatDau = (reader.IsDBNull(((int)PhimColumn.LichChieuBatDau - 1)))?null:(System.DateTime?)reader[((int)PhimColumn.LichChieuBatDau - 1)];
					c.MoTa = (reader.IsDBNull(((int)PhimColumn.MoTa - 1)))?null:(System.String)reader[((int)PhimColumn.MoTa - 1)];
					c.TrangThai = (System.Boolean)reader[((int)PhimColumn.TrangThai - 1)];
					c.LichChieuKetThuc = (reader.IsDBNull(((int)PhimColumn.LichChieuKetThuc - 1)))?null:(System.DateTime?)reader[((int)PhimColumn.LichChieuKetThuc - 1)];
                    //c.AnhMoTa = (reader.IsDBNull(((int)PhimColumn.AnhMoTa - 1))) ? null : (System.String)reader[((int)PhimColumn.AnhMoTa - 1)];
					c.EntityTrackingKey = key;
					c.AcceptChanges();
					c.SuppressEntityEvents = false;
				}
				rows.Add(c);
			}
		return rows;
		}		
		/// <summary>
		/// Refreshes the <see cref="TicketManager.Entities.Phim"/> object from the <see cref="IDataReader"/>.
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader"/> to read from.</param>
		/// <param name="entity">The <see cref="TicketManager.Entities.Phim"/> object to refresh.</param>
		public static void RefreshEntity(IDataReader reader, TicketManager.Entities.Phim entity)
		{
			if (!reader.Read()) return;
			
			entity.PhimId = (System.Int32)reader[((int)PhimColumn.PhimId - 1)];
			entity.TenPhim = (System.String)reader[((int)PhimColumn.TenPhim - 1)];
			entity.LichChieuBatDau = (reader.IsDBNull(((int)PhimColumn.LichChieuBatDau - 1)))?null:(System.DateTime?)reader[((int)PhimColumn.LichChieuBatDau - 1)];
			entity.MoTa = (reader.IsDBNull(((int)PhimColumn.MoTa - 1)))?null:(System.String)reader[((int)PhimColumn.MoTa - 1)];
			entity.TrangThai = (System.Boolean)reader[((int)PhimColumn.TrangThai - 1)];
			entity.LichChieuKetThuc = (reader.IsDBNull(((int)PhimColumn.LichChieuKetThuc - 1)))?null:(System.DateTime?)reader[((int)PhimColumn.LichChieuKetThuc - 1)];
            entity.AnhMoTa = (reader.IsDBNull(((int)PhimColumn.AnhMoTa - 1))) ? null : (System.String)reader[((int)PhimColumn.AnhMoTa - 1)];
			entity.AcceptChanges();
		}
		
		/// <summary>
		/// Refreshes the <see cref="TicketManager.Entities.Phim"/> object from the <see cref="DataSet"/>.
		/// </summary>
		/// <param name="dataSet">The <see cref="DataSet"/> to read from.</param>
		/// <param name="entity">The <see cref="TicketManager.Entities.Phim"/> object.</param>
		public static void RefreshEntity(DataSet dataSet, TicketManager.Entities.Phim entity)
		{
			DataRow dataRow = dataSet.Tables[0].Rows[0];
			
			entity.PhimId = (System.Int32)dataRow["PhimID"];
			entity.TenPhim = (System.String)dataRow["TenPhim"];
			entity.LichChieuBatDau = Convert.IsDBNull(dataRow["LichChieuBatDau"]) ? null : (System.DateTime?)dataRow["LichChieuBatDau"];
			entity.MoTa = Convert.IsDBNull(dataRow["MoTa"]) ? null : (System.String)dataRow["MoTa"];
			entity.TrangThai = (System.Boolean)dataRow["TrangThai"];
			entity.LichChieuKetThuc = Convert.IsDBNull(dataRow["LichChieuKetThuc"]) ? null : (System.DateTime?)dataRow["LichChieuKetThuc"];
            entity.AnhMoTa = Convert.IsDBNull(dataRow["AnhMoTa"]) ? null : (System.String)dataRow["AnhMoTa"];
			entity.AcceptChanges();
		}
		#endregion 
		
		#region DeepLoad Methods
		/// <summary>
		/// Deep Loads the <see cref="IEntity"/> object with criteria based of the child 
		/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
		/// </summary>
		/// <remarks>
		/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
		/// </remarks>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">The <see cref="TicketManager.Entities.Phim"/> object to load.</param>
		/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
		/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
		/// <param name="childTypes">TicketManager.Entities.Phim Property Collection Type Array To Include or Exclude from Load</param>
		/// <param name="innerList">A collection of child types for easy access.</param>
	    /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception>
	    /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception>
		public override void DeepLoad(TransactionManager transactionManager, TicketManager.Entities.Phim entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList)
		{
			if(entity == null)
				return;
			
			//used to hold DeepLoad method delegates and fire after all the local children have been loaded.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
			// Deep load child collections  - Call GetByPhimId methods when available
			
			#region VeCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<Ve>|VeCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'VeCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.VeCollection = DataRepository.VeProvider.GetByPhimId(transactionManager, entity.PhimId);

				if (deep && entity.VeCollection.Count > 0)
				{
					deepHandles.Add("VeCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<Ve>) DataRepository.VeProvider.DeepLoad,
						new object[] { transactionManager, entity.VeCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			//Fire all DeepLoad Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			deepHandles = null;
		}
		
		#endregion 
		
		#region DeepSave Methods

		/// <summary>
		/// Deep Save the entire object graph of the TicketManager.Entities.Phim object with criteria based of the child 
		/// Type property array and DeepSaveType.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entity">TicketManager.Entities.Phim instance</param>
		/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
		/// <param name="childTypes">TicketManager.Entities.Phim Property Collection Type Array To Include or Exclude from Save</param>
		/// <param name="innerList">A Hashtable of child types for easy access.</param>
		public override bool DeepSave(TransactionManager transactionManager, TicketManager.Entities.Phim entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList)
		{	
			if (entity == null)
				return false;
							
			#region Composite Parent Properties
			//Save Source Composite Properties, however, don't call deep save on them.  
			//So they only get saved a single level deep.
			#endregion Composite Parent Properties

			// Save Root Entity through Provider
			if (!entity.IsDeleted)
				this.Save(transactionManager, entity);
			
			//used to hold DeepSave method delegates and fire after all the local children have been saved.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
	
			#region List<Ve>
				if (CanDeepSave(entity.VeCollection, "List<Ve>|VeCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(Ve child in entity.VeCollection)
					{
						if(child.PhimIdSource != null)
						{
							child.PhimId = child.PhimIdSource.PhimId;
						}
						else
						{
							child.PhimId = entity.PhimId;
						}

					}

					if (entity.VeCollection.Count > 0 || entity.VeCollection.DeletedItems.Count > 0)
					{
						//DataRepository.VeProvider.Save(transactionManager, entity.VeCollection);
						
						deepHandles.Add("VeCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< Ve >) DataRepository.VeProvider.DeepSave,
							new object[] { transactionManager, entity.VeCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
			//Fire all DeepSave Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			
			// Save Root Entity through Provider, if not already saved in delete mode
			if (entity.IsDeleted)
				this.Save(transactionManager, entity);
				

			deepHandles = null;
						
			return true;
		}
		#endregion
	} // end class
	
	#region PhimChildEntityTypes
	
	///<summary>
	/// Enumeration used to expose the different child entity types 
	/// for child properties in <c>TicketManager.Entities.Phim</c>
	///</summary>
	public enum PhimChildEntityTypes
	{

		///<summary>
		/// Collection of <c>Phim</c> as OneToMany for VeCollection
		///</summary>
		[ChildEntityType(typeof(TList<Ve>))]
		VeCollection,
	}
	
	#endregion PhimChildEntityTypes
	
	#region PhimFilterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;PhimColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Phim"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class PhimFilterBuilder : SqlFilterBuilder<PhimColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PhimFilterBuilder class.
		/// </summary>
		public PhimFilterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the PhimFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public PhimFilterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the PhimFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public PhimFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion PhimFilterBuilder
	
	#region PhimParameterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;PhimColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Phim"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class PhimParameterBuilder : ParameterizedSqlFilterBuilder<PhimColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PhimParameterBuilder class.
		/// </summary>
		public PhimParameterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the PhimParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public PhimParameterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the PhimParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public PhimParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion PhimParameterBuilder
	
	#region PhimSortBuilder
    
    /// <summary>
    /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;PhimColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Phim"/> object.
    /// </summary>
    [CLSCompliant(true)]
    public class PhimSortBuilder : SqlSortBuilder<PhimColumn>
    {
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the PhimSqlSortBuilder class.
		/// </summary>
		public PhimSortBuilder() : base() { }

		#endregion Constructors

    }    
    #endregion PhimSortBuilder
	
} // end namespace
